package com.mini6410.EEPROM;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import com.mini6410.R;

public class EEPROMActivity extends Activity {
	public static final int MSG_UPDATE_UI = 0;
	public static final int MSG_GET_DATA = 1;

	private Button mButtonWrite = null;
	private Button mButtonRead = null;
	private EditText mEditTextWrite = null;
	private EditText mEditTextRead = null;

	private Editable mEditable = null;

	private WriteEEPROM mWriteEEPROM = null;
	private ReadEEPROM mReadEEPROM = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_PROGRESS);  
		setContentView(R.layout.eepromdemo);
		setProgressBarVisibility(true);

		initUI();
		initData();

	}

	public void initUI(){
		mButtonWrite = (Button)findViewById(R.id.Button_write);
		mButtonRead =  (Button)findViewById(R.id.Button_read);

		mButtonWrite.setOnClickListener(mClickListener);
		mButtonRead.setOnClickListener(mClickListener);

		mEditTextWrite = (EditText)findViewById(R.id.EditText_write);
		mEditTextRead = (EditText)findViewById(R.id.EditText_read);

		mEditable = mEditTextRead.getText();
	}

	public void initData(){
		mWriteEEPROM = new WriteEEPROM(mHandler);
		mReadEEPROM = new ReadEEPROM(mHandler);

	}


	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_UPDATE_UI:
				int pos = (int)msg.arg1;
				int length = (int)msg.arg2;
				setProgress(pos*10000/(length -1));
				break;
			case MSG_GET_DATA:
				Byte dataByte = (Byte)msg.obj;
				mEditable.append((char)dataByte.byteValue());
				mEditTextRead.setText(mEditable);
				break;
			default:
				break;
			}
		}
	};


	private Button.OnClickListener mClickListener = new Button.OnClickListener(){

		public void onClick(View v) {
			Button mButton = (Button)v;

			switch (mButton.getId()) {
			case R.id.Button_read:
				ReadDataIntoEEPROM();
				break;
			case R.id.Button_write:
				WriteDataIntoEEPROM();
				break;
			default:
				break;
			}

		}

	};

	public void WriteDataIntoEEPROM(){
		byte[] data = mEditTextWrite.getText().toString().getBytes();

		if(mWriteEEPROM != null)
			mWriteEEPROM.WriteData(data);
	}

	public void ReadDataIntoEEPROM(){
		mEditable.clear();
		if(mReadEEPROM != null)
			mReadEEPROM.ReadData();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}


}
